<?php
namespace app\app\controller;

use think\Controller;

class Message extends Controller {
    /*
     * app通知信息
     */
    public function message($username) {
        $retUser = model('AppUser')->get(['username'=>$username]);
        $ret = model('AppMessageOperate')->where(['user_id' => $retUser->id])->select();
        if($ret) {
            // 获取消息
            for($i = 0; $i<count($ret); $i++){
                $retMeg = model('AppMessages')->get(['id' => $ret[$i]->message_id]);
                $dataArr[$i] = array(
                    'id'      => $ret[$i] ->id,
                    'title'   => $retMeg ->m_title,
                    'content' => $retMeg ->m_content,
                    'date'    => $retMeg ->update_time,
                    'read'    => $ret[$i] ->is_read,
                    'delete'  => $ret[$i] ->is_delete,
                );
            }
        }
        return $dataArr;
    }
    
    /*
     * app通知信息状态
     */
    public function messageState($username) {
        $retUser = model('AppUser')->get(['username'=>$username]);
        $retMeg  = model('AppMessages')->all();
        $addMessage = array();
        for($i = 0; $i < count($retMeg); $i++) {
            $retMegOp = model('AppMessageOperate')->where(
                    ['user_id' => $retUser->id]
                )->where(
                    ['message_id' => $retMeg[$i]->id]
                )->select();
            // $retMegOp不存在则添加到消息操作表
            if(!($retMegOp)) {
                $addMessage[$i] = array(
                    'user_id'    => $retUser->id,
                    'message_id' => $retMeg[$i]->id,
                );
            } 
        }
        model('AppMessageOperate')->add($addMessage);
        // 找到消息操作表里指定用户的所有表数据
        $ret = model('AppMessageOperate')->where(['user_id' => $retUser ->id])->select();
        // 有未读消息则返回true，否则返回false
        for($j = 0; $j < count($ret); $j++){
            if($ret[$j]->is_read == 0) {
                if($ret[$j]->is_delete == 0) {
                    return true;
                }
            }
        }
        return false;
    }
    
    /*
     * app通知信息已阅读处理
     */
    public function megRead($id) {
        $ret = model('AppMessageOperate')->get(['id'=>$id]);
        $messageData = [
            'is_read' => true,
        ];
        $updateMessage= model('AppMessageOperate')->updateById($messageData, $ret->id);
        if(!$updateMessage) {
            return false;
        } else {
            return true;
        }
    }
    
    /*
     * app通知信息已删除处理
     */
    public function megDelete($id) {
        $ret = model('AppMessageOperate')->get(['id'=>$id]);
        $messageData = [
            'is_delete' => true,
        ];
        $updateMessage= model('AppMessageOperate')->updateById($messageData, $ret->id);
        if(!$updateMessage) {
            return false;
        } else {
            return true;
        }
    }
}
